;;
;;To use this method, you must
;;download prfile32.exe from http://www.lerup.com/printfile/
;;I got this printing solution from stackflow
;;

(setq is-win32 t)

(defun joc-make-fname-from-buffer-name (buffer-name-in)
  "Returns a valid filename from a given buffer name"
  (interactive "b")
  (save-match-data
    (let* ((start (string-match "[^ \*]" buffer-name-in))
           (end (string-match "[ \*]*$" buffer-name-in (match-end 0)))
           (rc (substring buffer-name-in start end)))
      ;; remove some special characters
      (while (string-match "[:]+" rc)
        (setq rc (replace-match "_" t t rc)))
      rc)))

(when is-win32
    (defun joc-print-buffer-or-region (prefix)
      "Prints buffer or region via PrintFile32.  If a prefix arg is set (via C-u) then
       the current region is printed, otherwise the current buffer is printed."

      (interactive "P")

      ;; ----- set the print directory, fname and args -----
      (let* ((print-dir (expand-file-name "~/emacs/print"))
             (print-fname (joc-make-fname-from-buffer-name (buffer-name)))
             (print-fullpath (concat print-dir "/" print-fname))
             (print-args "/delete")
             ;; ----- set rstart and rend to the current region -----
             (rstart (point-min)) (rend (point-max)))

        ;; ----- if prefix given, set them to region -----
        (if (and prefix)
            (if (and (point) (mark) (/= (point) (mark)))
                (progn (setq rstart (min (point) (mark)))
                       (setq rend (max (point) (mark))))
              (error "No region defined")))

        ;; ----- make the directory -----
        (if (not (file-directory-p print-dir))
            (make-directory print-dir))

        ;; ----- write buffer/region to a temp file, print it, delete directory -----
        (write-region rstart rend print-fullpath)
        (call-process "prfile32" nil t nil print-args print-fullpath)
        (delete-directory print-dir))))
